package com.bruan.reflect_demo;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.lang.reflect.Field;

public class ObjectFrame {
    /**
     *  保存任意对象的字段及其数据到文件中
     * @param o
     * @param path 文件路径
     */
    public static void saveObj(Object o,String path) {
        //创建打印流
        try(PrintStream printStream = new PrintStream(new FileOutputStream(path, true));
                ) {
            Class c = o.getClass();
            String cName = c.getSimpleName();
            printStream.println("-------------------"+cName+"---------------------------");
            //从类中提取全部成员
            Field[] fields = c.getDeclaredFields();
            for (Field field : fields) {
                //拿到成员变量的名字
                String name = field.getName();
                //拿到成员变量的值
                field.setAccessible(true);
                String val =field.get(o) + "";
                printStream.println(name+" = "+val);
            }
            printStream.println("--------------------------------------------------------");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
